package com.hrms.controller;

import com.hrms.dto.ApiResponse;
import com.hrms.entity.User;
import com.hrms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/profile")
    public ResponseEntity<ApiResponse<User>> getCurrentUser(Authentication authentication) {
        String username = authentication.getName();
        User user = userService.findByUsername(username);
        return ResponseEntity.ok(ApiResponse.success(user));
    }

    @PutMapping("/profile")
    public ResponseEntity<ApiResponse<User>> updateProfile(Authentication authentication,
                                                           @RequestBody User userDetails) {
        String username = authentication.getName();
        User updatedUser = userService.updateProfile(username, userDetails);
        return ResponseEntity.ok(ApiResponse.success("个人信息更新成功", updatedUser));
    }

    @PutMapping("/password")
    public ResponseEntity<ApiResponse<Void>> changePassword(Authentication authentication,
                                                           @RequestParam String oldPassword,
                                                           @RequestParam String newPassword) {
        String username = authentication.getName();
        userService.changePassword(username, oldPassword, newPassword);
        return ResponseEntity.ok(ApiResponse.success("密码修改成功", null));
    }
}
